package com.server;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Helper.FlightHelper;

public class SelectFlightServlet extends CustomerServlet
{
	private static final long serialVersionUID = 1L;
	private final String className = "Select Flight Servlet: ";
	
	String flightID = null;
	String username = null;
	
	@Override
	//@requires HttpServletRequest !=NULL,  HttpServletResponse !=NULL ;
    //@assignable flightID,username;
    //@ensures 	req.setAttribute("flightID", flightID) && req.setAttribute("username", username) && req.getRequestDispatcher("reservation/reserveFlight.jsp").forward(req, resp);	
	//@signals_only RuntimeException, IOException,ServletException;
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException
	{
		ConnectDB();
		String msg;
		flightID = req.getParameter("r1");
		username = req.getParameter("username");
		try
		{
			FlightHelper.Setup(connection);
			
			if (username.equals("null"))//make sure user has logged in
			{
				msg = "You must sign in to reserve a flight.";
				req.setAttribute("msg", msg);
				req.getRequestDispatcher("flight/search_error.jsp").forward(req, resp);
			}
			else if (flightID == null)//make sure user has chosen a flight
			{
				msg = "You did not select a flight.";
				req.setAttribute("msg", msg);
				req.setAttribute("username", username);
				req.getRequestDispatcher("flight/search_error.jsp").forward(req, resp);
			}
			else if (FlightHelper.IsFull(flightID))
			{
				msg = "This flight has no more vacancies.";
				req.setAttribute("msg", msg);
				req.setAttribute("username", username);
				req.getRequestDispatcher("flight/search_error.jsp").forward(req, resp);
			}
			else
			{	
				String flight = "'" + flightID + "'";
				req.setAttribute("flight", flight);
				
				req.setAttribute("flightID", flightID);
				req.setAttribute("username", username);
				req.getRequestDispatcher("reservation/reserveFlight.jsp").forward(req, resp);	
			}
		}
		catch (SQLException e1) 
		{
			msg = "Reservation Failed.";
			e1.printStackTrace();
			req.setAttribute("msg", msg);
			req.getRequestDispatcher("index_loggedin.jsp").forward(req, resp);	
		}
	}

}

